<template>
  <div class="p-2">

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--<el-col :span="1.5">-->
          <!--  <el-button type="primary" plain icon="Plus" @click="handleAdd"-->
          <!--    v-hasPermi="['basicPublic:referralRecords:add']">新增</el-button>-->
          <!--</el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="referralRecordsList" @selection-change="handleSelectionChange">
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="转入医院" align="center" prop="transferHospital" />
        <el-table-column label="转入科室" align="center" prop="transferDepartment" />
        <el-table-column label="身份证号" align="center" prop="idCard" width="170" />
        <el-table-column label="申请日期" align="center" prop="applyDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请机构" align="center" prop="applyAgency" width="180" />
        <el-table-column label="申请医生" align="center" prop="applyDoctor" width="180" />
        <el-table-column label="联系电话" align="center" prop="personalPhone" width="180" />
        <el-table-column label="转出原因" align="center" prop="transferOutReason" />

      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改转诊记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1000px" append-to-body>
      <el-form ref="referralRecordsFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="转入医院" prop="transferHospital">
              <el-input v-model="form.transferHospital" placeholder="请输入转入医院" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="转入科室" prop="transferDepartment">
              <el-input v-model="form.transferDepartment" placeholder="请输入转入科室" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请日期" prop="applyDate">
              <el-date-picker clearable v-model="form.applyDate" type="date" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择申请日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="申请机构">
              <el-input v-model="basicInfo.applyAgency" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="申请医生">
              <el-input v-model="basicInfo.applyDoctor" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input v-model="basicInfo.personalPhone" disabled />
            </el-form-item>
          </el-col>

          <!-- 居民信息标题 -->
          <el-col :span="24">
            <h3 style="font-size: 18px;margin-bottom: 15px"><strong>居民信息</strong></h3>
          </el-col>

          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input v-model="basicInfo.name" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input v-model="basicInfo.idCard" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="性别">
              <el-input v-model="basicInfo.gender" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="年龄">
              <el-input v-model="basicInfo.age" disabled />
            </el-form-item>
          </el-col>

          <!-- 转诊信息标题 -->
          <el-col :span="24">
            <h3 style="font-size: 18px;margin-bottom: 15px"><strong>转诊信息</strong></h3>
          </el-col>
        </el-row>
        <el-form-item label="初步印象" prop="initialImpressions">
          <el-input v-model="form.initialImpressions" placeholder="请输入初步印象" />
        </el-form-item>
        <el-form-item label="转出原因" prop="transferOutReason">
          <el-input v-model="form.transferOutReason" placeholder="请输入转出原因" />
        </el-form-item>
        <el-form-item label="主要既往史" prop="anamnesis">
          <el-input v-model="form.anamnesis" placeholder="请输入主要既往史" />
        </el-form-item>
        <el-form-item label="治疗过程" prop="treatmentProcess">
          <el-input v-model="form.treatmentProcess" placeholder="请输入治疗过程" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ReferralRecords" lang="ts">
import { listReferralRecords, getReferralRecords, delReferralRecords, addReferralRecords, updateReferralRecords, getPatientInfo } from '@/api/basicPublic/referralRecords';
import { ReferralRecordsVO, ReferralRecordsQuery, ReferralRecordsForm } from '@/api/basicPublic/referralRecords/types';
import { parseTime } from "../../../utils/ruoyi";
import { useRoute } from "vue-router";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const referralRecordsList = ref<ReferralRecordsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const referralRecordsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ReferralRecordsForm = {
  id: undefined,
  patientId: undefined,
  transferHospital: undefined,
  transferDepartment: undefined,
  applyDate: undefined,
  transferOutReason: undefined,
  initialImpressions: undefined,
  anamnesis: undefined,
  treatmentProcess: undefined,
}
const data = reactive<PageData<ReferralRecordsForm, ReferralRecordsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "id不能为空", trigger: "blur" }
    ],
    patientId: [
      { required: true, message: "患者id不能为空", trigger: "blur" }
    ],
    transferHospital: [
      { required: true, message: "转入医院不能为空", trigger: "blur" }
    ],
    transferDepartment: [
      { required: true, message: "转入科室不能为空", trigger: "blur" }
    ],
    applyDate: [
      { required: true, message: "申请日期不能为空", trigger: "blur" }
    ],
    transferOutReason: [
      { required: true, message: "转出原因不能为空", trigger: "blur" }
    ],
    initialImpressions: [
      { required: true, message: "初步印象不能为空", trigger: "blur" }
    ],
    anamnesis: [
      { required: true, message: "主要既往史不能为空", trigger: "blur" }
    ],
    treatmentProcess: [
      { required: true, message: "治疗过程不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询转诊记录列表 */
const route = useRoute()
watch(() => route.query.id, () => {
  route.query.id ? getList() : ""
})
const getList = async () => {
  data.queryParams.patientId = route.query.id
  loading.value = true;
  const res = await listReferralRecords(queryParams.value);
  referralRecordsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

let basicInfo = {
  name: '',
  idCard: '',
  gender: '',
  age: '',
  personalPhone: '',
  applyDoctor: '',
  applyAgency: ''
}
const getBasicInfo = async () => {
  const res = await getPatientInfo(route.query.id)
  console.log(basicInfo,'=');

  basicInfo = res.data;
  basicInfo.applyAgency = res.data && res.data.documentationUnitName ? res.data.documentationUnitName: '-'
  basicInfo.applyDoctor = res.data && res.data.dutyDoctorName ? res.data.dutyDoctorName:'-'
  basicInfo.age = calculateAge(res.data.idCard).toString();
}

/** 根据身份证计算年龄的方法 */
const calculateAge = (idCard: string) => {
  const birthDate = idCard.substring(6, 14);
  const year = parseInt(birthDate.substring(0, 4), 10);
  const month = parseInt(birthDate.substring(4, 6), 10);
  const day = parseInt(birthDate.substring(6, 8), 10);

  const today = new Date();
  let age = today.getFullYear() - year;

  const monthDifference = today.getMonth() - month;
  if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < day)) {
    age--;
  }

  return age;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  referralRecordsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ReferralRecordsVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加转诊记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ReferralRecordsVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getReferralRecords(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改转诊记录";
}

/** 提交按钮 */
const submitForm = () => {
  form.value.patientId = route.query.id
  referralRecordsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateReferralRecords(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addReferralRecords(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ReferralRecordsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除转诊记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delReferralRecords(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('basicPublic/referralRecords/export', {
    ...queryParams.value
  }, `referralRecords_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  getBasicInfo();
});
</script>
